package com.cxx.purchasecharge.component.controller;

import java.io.File;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cxx.purchasecharge.component.bean.ActionResult;
import com.cxx.purchasecharge.component.bean.ActionResult.ActionResultStatus;
import com.cxx.purchasecharge.component.utils.AjaxUtils;
import com.cxx.purchasecharge.component.utils.FileLoadUtils;
import com.cxx.purchasecharge.dal.BackupAndRestore;

@Controller
@RequestMapping ("/dataBackupAndLoad")
public class BackupAndRestoreManager
{
    private static final Logger LOGGER = Logger.getLogger (BackupAndRestoreManager.class);

    private String viewName = "backupAndRestoreManagement";
    @Autowired
    private BackupAndRestore dataBackupAndLoad;

    @RequestMapping (value = "/")
    public String initView (ModelMap model)
    {
        return viewName;
    }

    @SuppressWarnings ("all")
    @RequestMapping (value = "/backup", method = RequestMethod.GET)
    public @ResponseBody
    String backup (HttpServletRequest request, HttpServletResponse response)
    {
        String dir = request.getRealPath ("/") + "temp";
        File tmpFile = dataBackupAndLoad.backup (dir);
        FileLoadUtils.download (request, response, tmpFile, "");
        // delete file
        tmpFile.delete ();
        return "";
    }

    @SuppressWarnings ("all")
    @RequestMapping (value = "/load", method = RequestMethod.POST)
    public @ResponseBody
    String load (HttpServletRequest request, HttpServletResponse response)
    {
        ActionResult ar = null;
        try
        {
            String dir = request.getRealPath ("/") + "temp";
            File tmpFile = FileLoadUtils.upload (request, response, dir);
            dataBackupAndLoad.load (tmpFile);
            ar = ActionResult.createActionResult ().withStatus (ActionResultStatus.OK).build ();
            // delete file
            tmpFile.delete ();
        }
        catch (Exception e)
        {
            LOGGER.warn ("Load data fail", e);
            ar = ActionResult.createActionResult ().withStatus (ActionResultStatus.INTERNAL_SERVER_ERROR).build ();
        }
        return AjaxUtils.getJsonObject (ar);
    }

    public String getViewName ()
    {
        return viewName;
    }

    public void setViewName (String viewName)
    {
        this.viewName = viewName;
    }
}
